﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace iTunesPlaycountUpdater
{
    static class LastFmApiResponseParser
    {
        public static List<LastFmTrack> ParseGetTracksResponse(XElement response)
        {
            if (response == null)
                throw new ArgumentException("Response cannot be null", "response");
            List<LastFmTrack> tracks = new List<LastFmTrack>();

            foreach (var item in response.Elements())
            {
                tracks.Add(
                    new LastFmTrack(
                        ValueOrEmpty(item.Element("artist")), // Nested <name> tag in <artist>/<album> is taken care of.
                        ValueOrEmpty(item.Element("album")),
                        item.Element("name").Value,
                        int.Parse(item.Element("playcount").Value)
                        )
                        );
            }

            return tracks;
        }

        private static string ValueOrEmpty(XElement element)
        {
            if (element == null)
                return "";
            return element.Element("name").Value;
        }
    }
}
